﻿using System;
using System.Configuration;
using System.Data;
using mojoPortal.Net;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using ud_gSDMS.Code_Service;
using mojoPortal.Business.WebHelpers;
namespace ud_gSDMS.contract
{
    public partial class Contract_Accept : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private string _id;
        private SiteUser _siteUser;
        

        void Page_Load(object sender, EventArgs e)
        {
            //if (!UserCanEditPage() || !UserCanViewPage())
            //{
            //    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");

            _siteUser = SiteUtils.GetCurrentSiteUser();
            if (_siteUser == null)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }


            if (!Page.IsPostBack)
            {
                PopulateLabels();
                PopulateControls();
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    _id = Request["id"];
                    LoadData(_id);
                }
            }
        }
        private void PopulateLabels()
        {

        }
        private void PopulateControls()
        {
            var minDay = Convert.ToDateTime(ConfigurationManager.AppSettings["MinDay"]);
            var maxDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
            datContract_Date.MinDate = minDay;
            datContract_Date.MaxDate = maxDay;

            datStart_Date.MinDate = minDay;
            datStart_Date.MaxDate = new DateTime(maxDay.Year + 1, maxDay.Month, maxDay.Day);

            datEnd_Date.MaxDate = minDay;
            datEnd_Date.MaxDate = new DateTime(maxDay.Year + 1, maxDay.Month, maxDay.Day);

            var db = new gSDMS_DataLinq();
            var tbUser = Library.LINQToDataTable(db, db.mp_Users);
            cboCat_Product_Package_ID.DataValueField = "CAT_Product_Package_ID";
            cboCat_Product_Package_ID.DataTextField = "Name";
            cboCat_Product_Package_ID.DataSource = Library.LINQToDataTable(db, db.ud_gSDMS_CAT_PRODUCT_PACKAGEs);
            cboCat_Product_Package_ID.DataBind();

            cboAccount_Manager.DataValueField = "UserID";
            cboAccount_Manager.DataTextField = "LoginName";
            cboAccount_Manager.DataSource = tbUser;
            cboAccount_Manager.DataBind();

            cboAssigned_To.DataValueField = "UserID";
            cboAssigned_To.DataTextField = "LoginName";
            cboAssigned_To.DataSource = tbUser;
            cboAssigned_To.DataBind();

            //RECEIVING & TRANFER
            cboStatus.DataValueField = "CAT_Project_Step_ID";
            cboStatus.DataTextField = "Name";
            cboStatus.DataSource = Library.LINQToDataTable(db, db.ud_gSDMS_CAT_PROJECT_STEPs);
            cboStatus.DataBind();

            cboProject_Leader.DataValueField = "UserID";
            cboProject_Leader.DataTextField = "LoginName";
            cboProject_Leader.DataSource = gSDMS_BL.mp_User_Search(null, null, null, null, null, null, "11");
            cboProject_Leader.DataBind();
            
            cboMemberList.DataValueField = "UserID";
            cboMemberList.DataTextField = "LoginName";
            cboMemberList.DataSource = gSDMS_BL.mp_User_Search(null, null, null, null, null, null, "5|2|3");
            cboMemberList.DataBind();
            cboMemberList.Items.Insert(0, "");

            cboRole.DataValueField = "RoleID";
            cboRole.DataTextField = "DisplayName";
            cboRole.DataSource = gSDMS_BL.mp_Role_Search("2|13|17|18|11" , null , null );
            cboRole.DataBind();
            cboRole.Items.Insert(0, "");

            var contract_Status = gSDMS_BL.ud_gSDMS_CAT_CONTRACT_STATUS_Lst();

            cboContract_Status.DataValueField = "CAT_Contract_Status_ID";
            cboContract_Status.DataTextField = "Name";
            cboContract_Status.DataSource = contract_Status;
            cboContract_Status.DataBind();


            //Set status
            const bool readOnly = true;
            txtContract_Code.ReadOnly = readOnly;
            txtContract_Name.ReadOnly = readOnly;
            datContract_Date.Enabled = !readOnly;
            cboCat_Product_Package_ID.Enabled = !readOnly;
            datStart_Date.Enabled = !readOnly;
            datEnd_Date.Enabled = !readOnly;
            txtResource.ReadOnly = readOnly;

            txtCustomer_Code.ReadOnly = readOnly;
            txtCustomer_Name.ReadOnly = readOnly;
            txtCustomer_Phone.ReadOnly = readOnly;
            txtCustomer_Fax.ReadOnly = readOnly;
            txtCustomer_Email.ReadOnly = readOnly;
            txtContact_Name_1.ReadOnly = readOnly;
            txtContact_Email_1.ReadOnly = readOnly;
            txtContact_Phone_1.ReadOnly = readOnly;
            txtContact_Name_2.ReadOnly = readOnly;
            txtContact_Phone_2.ReadOnly = readOnly;
            txtContact_Email_2.ReadOnly = readOnly;

            cboAccount_Manager.Enabled = !readOnly;
            cboAssigned_To.Enabled = !readOnly;
            txtNotes.WebEditor.ToolBar = mojoPortal.Web.Editor.ToolBar.Full;
            txtNotes.WebEditor.Height = 200;
            //cboCAT_Contract_Status_ID.Enabled = !readOnly;

        }
        private void LoadData(string id)
        {
            if (string.IsNullOrEmpty(id)) return;

            var o = gSDMS_BL.ud_gSDMS_CONTRACT_Get(id);
            if (o != null)
            {
                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "12|1") == false
                   )
                {
                    if (o.Assigned_To != _siteUser.UserId)
                    {
                        WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                    }
                }

                hidId.Value = o.Contract_ID.ToString();
                if (o.CreatedOn != null) hidCreatedOn.Value = o.CreatedOn.Value.ToShortDateString();
                txtContract_Code.Text = o.Contract_Code;
                txtContract_Name.Text = o.Contract_Name;
                datContract_Date.SelectedDate = o.Contract_Date;
                cboCat_Product_Package_ID.SelectedValue = o.Cat_Product_Package_ID.ToString();
                if (o.Start_Date != null) datStart_Date.SelectedDate = o.Start_Date;
                if (o.End_Date != null) datEnd_Date.SelectedDate = o.End_Date;
                txtResource.Text = o.Resource.ToString();
                txtCustomer_Code.Text = o.Customer_Code;
                txtCustomer_Name.Text = o.Customer_Name;
                txtCustomer_Phone.Text = o.Customer_Phone;
                txtCustomer_Fax.Text = o.Customer_Fax;
                txtCustomer_Email.Text = o.Customer_Email;
                txtCompany_Address.Text = o.Customer_Address;
                txtContact_Name_1.Text = o.Contact_Name_1;
                txtContact_Email_1.Text = o.Contact_Email_1;
                txtContact_Phone_1.Text = o.Contact_Phone_1;
                txtContact_Name_2.Text = o.Contact_Name_2;
                txtContact_Email_2.Text = o.Contact_Email_2;
                txtContact_Phone_2.Text = o.Contact_Phone_2;
                if (o.Account_Manager != null) cboAccount_Manager.SelectedValue = o.Account_Manager.Value.ToString();
                if (o.Assigned_To != null) cboAssigned_To.SelectedValue = o.Assigned_To.Value.ToString();
                txtNotes.Text = o.Notes;
                cboContract_Status.SelectedValue = o.CAT_Contract_Status_ID.ToString();

                if (o.ud_gSDMS_PROJECTs.Count > 0)
                {
                    var proj = o.ud_gSDMS_PROJECTs[0];
                    hidProject_ID.Value = proj.Project_ID.ToString();//hide
                    if (proj.CreatedOn != null) hidCreatedOn_Project.Value = proj.CreatedOn.Value.ToString();//hide

                    if (proj.CAT_Project_Step_ID != null)
                        cboStatus.SelectedValue = proj.CAT_Project_Step_ID.Value.ToString();
                    txtCode_Project.Text = proj.Code;
                    txtResourceProject.Text = proj.Resource.ToString();
                    if (proj.Kickoff_Date != null) datKickoff_Date.SelectedDate = proj.Kickoff_Date;
                    if (proj.End_Date != null) datEnd_DateProject.SelectedDate = proj.End_Date;
                    if (proj.Project_Leader != null)
                        cboProject_Leader.SelectedValue = proj.Project_Leader.Value.ToString();
                    

                    var c = proj.ud_gSDMS_PROJECT_ROLEs.Count;
                    if (c > 0)
                    {
                        var dataTable = CreateTable();
                        var projRols = proj.ud_gSDMS_PROJECT_ROLEs;
                        for (var i = 0; i < c; i++)
                        {
                            var dataRow = dataTable.NewRow();
                            var projRol = projRols[i];
                            dataRow["Project_Role_ID"] = projRol.Project_Role_ID;
                            dataRow["UserID"] = projRol.UserID;
                            dataRow["UserName"] = projRol.mp_User.LoginName;
                            dataRow["Name"] = projRol.mp_User.Name;
                            dataRow["RoleID"] = projRol.RoleID;
;
                            dataRow["RoleName"] = projRol.mp_Role.DisplayName;
                            dataTable.Rows.Add(dataRow);
                        }
                        ViewState["listMember"] = dataTable;

                        LoadGrid();
                    }
                }


                //end
                if (txtCode_Project.Text == "")
                    txtCode_Project.Text = string.Format("{0}_{1}_{2}_", o.ud_gSDMS_CAT_PRODUCT_PACKAGE.Code,
                                                         DateTime.Now.Year.ToString(), o.Contract_Code.Substring(0, 3));
            }
        }
        private void LoadGrid()
        {
            if (ViewState["listMember"] != null)
            {
                var data = (DataTable)ViewState["listMember"];
                grdMember.DataSource = data;
                grdMember.DataBind();
            }
        }
        private bool CheckData()
        {
            var isValid = true;

            var t = txtCode_Project.Text;
            if (t.Split('_').Length < 4 || t.Split('_')[3] == "")
            {
                isValid = false;
                ReqCode_Project.IsValid = false;
                txtCode_Project.Focus();
                return isValid;
            }

            return isValid;
        }
        private DataTable CreateTable()
        {
            var dataTable = new DataTable();
            DataColumn col;

            col = new DataColumn("Project_Role_ID");
            dataTable.Columns.Add(col);

            col = new DataColumn("UserID");
            dataTable.Columns.Add(col);

            col = new DataColumn("UserName");
            dataTable.Columns.Add(col);

            col = new DataColumn("Name");
            dataTable.Columns.Add(col);

            col = new DataColumn("RoleID");
            dataTable.Columns.Add(col);
            col = new DataColumn("RoleName");
            dataTable.Columns.Add(col);
            return dataTable;
        }

        #region event
        void btnSave_Click(object sender, EventArgs e)
        {
            //try
            //{
                if (!CheckData()) return;

                _id = hidProject_ID.Value;
                string cId = hidId.Value;
                var userSite = SiteUtils.GetCurrentSiteUser();

                gSDMS_BL.ud_gSDMS_CONTRACT_Upd( ref cId, null, null , null , null, null, 
                                                null, null, null,null,null,null , null, null, 
                                                null, null, null, null, null, null, null, null, null, 
                                                cboContract_Status.SelectedValue, null, null, true);

                gSDMS_BL.ud_gSDMS_PROJECT_Upd(ref _id, hidId.Value, txtCode_Project.Text, txtContract_Name.Text,
                                              datKickoff_Date.DateInput.Text != "" ? datKickoff_Date.SelectedDate.Value.ToString() : null ,
                                              datEnd_DateProject.DateInput.Text != "" ? datEnd_DateProject.SelectedDate.Value.ToString() : null,
                                              txtResourceProject.Text, cboProject_Leader.SelectedValue, cboAssigned_To.SelectedValue,
                                              cboStatus.SelectedValue,
                                              cboContract_Status.SelectedValue,
                                              userSite.UserId.ToString(),
                                              hidCreatedOn_Project.Value == "" ? DateTime.Now.ToString() : hidCreatedOn_Project.Value, true);

 
                if (ViewState["listMember_Del"] != null)
                {
                    var listMember_Del = (DataTable) ViewState["listMember_Del"];
                    foreach (DataRow row in listMember_Del.Rows)
                    {
                        if (row["Project_Role_ID"] != null && row["Project_Role_ID"].ToString() != "")
                        {
                            var Project_Role_ID = row["Project_Role_ID"].ToString();
                            gSDMS_BL.ud_gSDMS_PROJECT_ROLE_Del(Project_Role_ID, null);
                        }
                    }
                }
                DataTable listMember;
                if (ViewState["listMember"] != null)
                {
                    listMember = (DataTable) ViewState["listMember"];
                    var Project_Role_ID = string.Empty;
                    foreach (DataRow row in listMember.Rows)
                    {
                        if (row["Project_Role_ID"] != null) Project_Role_ID = row["Project_Role_ID"].ToString();
                        gSDMS_BL.ud_gSDMS_PROJECT_ROLE_Upd(ref Project_Role_ID, _id, row["UserID"].ToString(), row["RoleID"].ToString(), true);
                    }
                    if (chkSendEmail.Checked)
                    {
                        string from, to, msg;
                        msg = "";
                        var userManager = _siteUser;
                        var cc = gSDMS_BL.mp_User_Lst("12");
                        var assigned = gSDMS_BL.mp_User_get(cboProject_Leader.SelectedValue, null);

                        if (cboContract_Status.Text == "Accepted")
                        {
                                var emailFrom = userManager.Email;
                                var emailCc = "";
                                foreach (var p in cc)
                                {
                                    var email = p.Email;
                                    emailCc += email + ",";
                                }

                                var emailTo = assigned.Email;
                                var subject = string.Format("[gSDMS-CONTRACT] PLEASE ACCEPT NEW PROJECT: {0} FROM gSDMS", txtCode_Project.Text);
                                var textBody = "Dear " + assigned.LoginName + "<br/><br/> You have a new project: <b>" + txtCode_Project.Text + "</b> from contract <b>" + txtContract_Name.Text + "</b><br/><br/> The project will begin from <b><u>" + datKickoff_Date.SelectedDate.Value.ToShortDateString() + "</b></u> to <b><u>"
                                    + datEnd_Date.SelectedDate.Value.ToShortDateString() + "</b></u>" +
                                    "<br/><br/> Please enter follow link to view detail :" + SiteRoot + "/gsdmsmodule/contract/Contract_Cat.aspx" +  "<br/><br/> Regard,<br/> " + userManager.LoginName;
                                var siteGuid = siteSettings.SiteGuid;
                                Library.SendMail(emailFrom, emailTo, emailCc, string.Empty, subject, textBody, siteGuid);
                         }
                            else
                            {
                                var emailFrom = userManager.Email;
                                var emailCc = "";
                                foreach (var p in cc)
                                {
                                    var email = p.Email;
                                    emailCc += email + ",";
                                }

                                var emailTo = assigned.Email;
                                var subject = string.Format("[gSDMS-CONTRACT] THE STATUS CONTRACT {0} HAS BEEN CHANGED", txtCode_Project.Text);
                                var textBody = "Dear " + assigned.LoginName + "<br/><br/>The status of contract : <b>"  + txtContract_Name.Text + "</b> (Code: " + txtContract_Code + ") has been changed to <b>" + cboContract_Status.Text + "</b>"
                                     +
                                    "<br/><br/> Please enter follow link to view detail :" + SiteRoot + "/gsdmsmodule/contract/Contract_Cat.aspx" +  "<br/><br/> Regard,<br/> " + userManager.LoginName;
                                var siteGuid = siteSettings.SiteGuid;
                                Library.SendMail(emailFrom, emailTo, emailCc, string.Empty, subject, textBody, siteGuid);
                            }
                                

                                //if (row["Project_Role_ID"] != null) Project_Role_ID = row["Project_Role_ID"].ToString();
                                //gSDMS_BL.ud_gSDMS_PROJECT_ROLE_Upd(ref Project_Role_ID, _id, row["UserID"].ToString(), row["CAT_User_Role_ID"].ToString(), true);
                            
                        }
                    }
    
                        Response.Redirect("/gsdmsmodule/contract/contract_cat.aspx");
            //}
            //catch (Exception ex)
            //{
            //    lblMes.Text = ex.Message;
            //    lblMes.Visible = true;
            //}
        }

        void datContract_Date_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {
            if (datContract_Date.SelectedDate != null)
            {
                datStart_Date.MinDate = (DateTime) datContract_Date.SelectedDate;
            }
        }

        void datStart_Date_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {
            if (datStart_Date.SelectedDate != null)
            {
                datEnd_Date.MinDate = (DateTime)datStart_Date.SelectedDate;
            }
        }
        
        void datEnd_Date_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {

        }
        
        void btnAdd_Click(object sender, EventArgs e)
        {
            DataTable data;
            if (ViewState["listMember"] == null)
                data = CreateTable();
            else
                data = (DataTable) ViewState["listMember"];

            var user = gSDMS_BL.mp_User_get(cboMemberList.SelectedValue, null);
            var row = data.NewRow();
            row["UserID"] = user.UserID;
            row["UserName"] = user.LoginName;
            row["Name"] = user.Name;
            row["RoleID"] = cboRole.SelectedValue;
            row["RoleName"] = cboRole.SelectedItem.Text;
            data.Rows.Add(row);

            ViewState["listMember"] = data;

            cboMemberList.SelectedValue = null;
            cboRole.SelectedValue = null;

            LoadGrid();

        }

        void grdMember_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            if (e.CommandName == "delete" && ViewState["listMember"] != null)
            {
                //var dataTable = (DataTable)ViewState["listMember"];
                //var userName = e.CommandArgument.ToString();
                //var row = dataTable.Select(string.Format("UserName='{0}'", userName))[0];

                var dataTable = (DataTable)ViewState["listMember"];
                var index = Convert.ToInt32(e.CommandArgument) - 1;
                var row = dataTable.Rows[index];

                //Backup Delete row
                
                if (row["Project_Role_ID"] != null && row["Project_Role_ID"].ToString() != "")
                {
                    DataTable dataTableDel;
                    if (ViewState["listMember_Del"] != null)
                        dataTableDel = (DataTable)ViewState["listMember_Del"];
                    else
                        dataTableDel = CreateTable();

                    dataTableDel.ImportRow(row);
                    ViewState["listMember_Del"] = dataTableDel;
                }

                //Delete
                dataTable.Rows.Remove(row); 
                ViewState["listMember"] = dataTable;

                grdMember.DataSource = dataTable;
                grdMember.DataBind();
            }
        }

        void grdMember_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
        {
            LoadGrid();
        }
        #endregion event

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);

            btnSave.Click+=btnSave_Click;
            datContract_Date.SelectedDateChanged += datContract_Date_SelectedDateChanged;
            datStart_Date.SelectedDateChanged += datStart_Date_SelectedDateChanged;
            datEnd_Date.SelectedDateChanged += datEnd_Date_SelectedDateChanged;
            btnAdd.Click += btnAdd_Click;
            SiteUtils.SetupEditor(txtNotes);

            grdMember.RowCommand += grdMember_RowCommand;
            grdMember.RowDeleting += grdMember_RowDeleting;
            //btnFinish.Click += btnFinish_Click;
            SuppressPageMenu();
        }

        //void btnFinish_Click(object sender, EventArgs e)
        //{
        //    WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
        //}

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion

        protected void txtContract_Code_TextChanged(object sender, EventArgs e)
        {

        }
    }
}